import * as utils from "@/assets/utils/util.js";

class sttWsClass{
    constructor(url,appkey)
    {
        this.wxUrl = url;
        this.ws = null;
        this.appkey = appkey;
        this._mediaRecorder = null; 
        this.recorderStatus = 0; //0 暂停  1开始
        this.tempTimer = null;
        this.durTime = 2000;
        this.content = "";
        this.init();
    }

    init()
    {
        this.initMediaStreamSource();
    }

    start()
    {
        this.content = "";
        this.ws = new WebSocket(this.wxUrl);
        this.ws.binaryType = 'arraybuffer';

        this.ws.addEventListener('open',  this.onOpen.bind(this));
        this.ws.addEventListener('message',  this.onMessage.bind(this));
        this.ws.addEventListener('close',  this.onClose.bind(this));
    }


    stop()
    {
        let sendData = {
            "apiType":"aly",
            "name" : "stop",
            "appkey": this.appKey
        };
        this.ws.send(JSON.stringify(sendData));
        this.recorderStatus = 0;
    }

    close()
    {
        if(this.ws)
        {
            this.ws.close();
        }
    }

    initMediaStreamSource()
    {
        let _self = this;
        navigator.mediaDevices.getUserMedia({ audio: true })
        .then(stream => {
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            const source = audioContext.createMediaStreamSource(stream);
            const processor = audioContext.createScriptProcessor(4096, 1, 1);

            source.connect(processor);
            processor.connect(audioContext.destination);

            processor.onaudioprocess = async (e) => {
                if(_self.recorderStatus == 0) return;
                const inputBuffer = e.inputBuffer.getChannelData(0);
                const downsampledBuffer = await utils.downsampleBuffer(inputBuffer, audioContext.sampleRate, 16000);
                const pcm16Buffer = utils.floatTo16BitPCM(downsampledBuffer);
                if(_self.ws  && _self.ws.readyState == 1)
                {
                    _self.ws.send(pcm16Buffer);
                }
            };

            _self._mediaRecorder = new MediaRecorder(stream);
            _self._mediaRecorder.onstop = () => {
                console.log('mediaRecorder stop');
            };
            // _self._mediaRecorder.stop();
            console.log(_self._mediaRecorder);
        });
    }

    onOpen(event)
    {
       
    }

    onMessage(event)
    {
        let data = JSON.parse(event.data);
        if(data.status == 200)
        {
            let actionName = data.name;
            let sendData = {};
            switch(actionName)
            {
                case 'connected':
                    sendData = {
                        "apiType":"aly",
                        "appkey": this.appkey,
                        "name" : "start",
                        "format" : "PCM",
                        "sample_rate":16000
                    }
                    this.ws.send(JSON.stringify(sendData));
                    // _self._mediaRecorder.start();
                
                    break;
                case 'started':
                    this.recorderStatus = 1;
                    break;
                case 'resultChanged':
                case 'sentenceEnd':
                    if(data.content.length > this.content.length)
                    {
                        this.content = data.content;
                    }
                    break;
                case 'completed':
                    if(data.content.length > this.content.length)
                    {
                        this.content = data.content;
                    }
                    this.OnCompleted(this.content);
                    this.close();
                    break;
            }

        }
    }


    onClose(event)
    {
        this.ws.removeEventListener('open',  this.onOpen.bind(this));
        this.ws.removeEventListener('message',  this.onMessage.bind(this));
        this.ws.removeEventListener('close',  this.onClose.bind(this));
        this.ws = null;
    }

    OnCompleted(content) { }

}


export default sttWsClass;